package com.aiyige.page.detail.adpater;

import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.aiyige.R;
import com.aiyige.model.moment.entity.Moment;
import com.aiyige.model.moment.entity.Praise;
import com.aiyige.model.request.PraiseRequest;
import com.aiyige.model.sns.Comment;
import com.aiyige.page.login.LoginPage;
import com.aiyige.page.login.model.impl.LoginManager;
import com.aiyige.page.user.UserPage;
import com.aiyige.utils.GlideUtil;
import com.aiyige.utils.TimeUtils;
import com.aiyige.utils.ToastX;
import com.alibaba.fastjson.JSON;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;

import java.io.IOException;
import java.util.LinkedList;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by zhuyakun on 2017/10/26.
 */

public class DetailAdapter extends BaseQuickAdapter<Comment, BaseViewHolder> {

    RequestOptions circleOptions = RequestOptions.circleCropTransform();

    Moment moment;
    public DetailAdapter() {
        super(new LinkedList<Comment>());
    }

    @Override
    protected void convert(BaseViewHolder helper, Comment item) {
        ((ViewHolder)helper).bindData(item);
    }

    @Override
    protected BaseViewHolder onCreateDefViewHolder(ViewGroup parent, int viewType) {
        BaseViewHolder baseViewHolder = new ViewHolder(getItemView(R.layout.item_detail_comment, parent));
        return baseViewHolder;
    }

    public void setMoment(Moment moment) {
        this.moment = moment;
    }

    public class ViewHolder extends BaseViewHolder {

        @BindView(R.id.iv_head)
        ImageView tvHead;
        @BindView(R.id.comment_title_layout)
        View commentTitleLayout;

        @BindView(R.id.text_name)
        TextView tvUserName;
        @BindView(R.id.text_comment)
        TextView tvComment;
        @BindView(R.id.text_date)
        TextView tvData;
        @BindView(R.id.item_comment_reply)
        View replyView;
        @BindView(R.id.original_comment_username)
        TextView tvOriginalUserName;
        @BindView(R.id.original_comment_content)
        TextView tvOriginalComment;
        @BindView(R.id.likeLayout)
        View llLike;
        @BindView(R.id.likeIv)
        ImageView ivLike;
        @BindView(R.id.text_like)
        TextView tvLikeCount;

        @BindView(R.id.tv_delete_tag)
        TextView tvDeleteTag;




        public ViewHolder(View view) {
            super(view);
            ButterKnife.bind(this, view);
        }

        public void bindData(final Comment item) {
            final Comment.CreatorBackup creatorBackup = item.getCreatorBackup();
            if (creatorBackup != null) {
                GlideUtil.with(mContext).small().loadAvatar(creatorBackup.getAvatar()).into(tvHead);
                tvUserName.setText(creatorBackup.getName());
            }
            tvComment.setText(item.getContent());
            if (item.getCreateTime() != null) {
                tvData.setText(TimeUtils.getStandardDate((item.getCreateTime())+""));
            }
            // 带回复的
            Comment replyComment = item.getObjectBackup();
            if (replyComment != null && item.getObjectType().equals(Comment.comment) && replyComment.isValid()) {
                replyView.setVisibility(View.VISIBLE);
                Comment.CreatorBackup replyCreatorBackup = replyComment.getCreatorBackup();
                tvOriginalUserName.setText(mContext.getString(R.string.original_comment)+(replyCreatorBackup != null ?replyCreatorBackup.getName():""));
                tvOriginalComment.setText(replyComment.getContent());
            } else {
                replyView.setVisibility(View.GONE);
            }
            if (replyComment != null && !replyComment.isValid()) {
                tvDeleteTag.setVisibility(View.VISIBLE);
            }
            final Comment.StatisticsBackup statisticsBackup = item.getStatisticsBackup();
            final Comment.MineBackup mineBackup = item.getMineBackup();
            llLike.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (!LoginManager.isLogin()) {
                        LoginPage.start();
                        return;
                    }
                    if (!TextUtils.isEmpty((String) llLike.getTag())) {
                        return;
                    }
                    llLike.setTag("requesting");
                    if (mineBackup != null && mineBackup.iAmPraised()) {
                        (new PraiseRequest()).deletePraises(mineBackup.getPraiseId()).enqueue(new Callback<ResponseBody>() {
                            @Override
                            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                                llLike.setTag(null);
                                try {
                                    if (response.isSuccessful()) {
                                        mineBackup.setPraiseId(null);
                                        statisticsBackup.setPraiseCount(statisticsBackup.getPraiseCount()-1);
                                        notifyDataSetChanged();
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }

                            @Override
                            public void onFailure(Call<ResponseBody> call, Throwable t) {
                                llLike.setTag(null);
                                if (t != null && !TextUtils.isEmpty(t.getMessage())) {
                                    ToastX.show(t.getMessage());
                                }
                            }
                        });
                    } else {
                        Praise praise = Praise.newBuilder().objectId(item.getId()).objectType("comment").subject(moment.getSubject()).build();
                        (new PraiseRequest()).addPraises(praise).enqueue(new Callback<ResponseBody>() {
                            @Override
                            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                                llLike.setTag(null);
                                try {
                                    if (response.isSuccessful()) {
                                        String json = response.body() != null ? response.body().string():"";
                                        Praise parseObject = JSON.parseObject(json, Praise.class);
                                        if (parseObject != null && !TextUtils.isEmpty(parseObject.getId())) {
                                            if (mineBackup != null) {
                                                mineBackup.setPraiseId(parseObject.getId());
                                            }
                                            statisticsBackup.setPraiseCount(statisticsBackup.getPraiseCount()+1);
                                            notifyDataSetChanged();
                                        }
                                    }
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }

                            }

                            @Override
                            public void onFailure(Call<ResponseBody> call, Throwable t) {
                                llLike.setTag(null);
                                if (t != null && !TextUtils.isEmpty(t.getMessage())) {
                                    ToastX.show(t.getMessage());
                                }
                            }
                        });
                    }

                }
            });
            if (mineBackup != null) {
                ivLike.setSelected(mineBackup.iAmPraised());
            }
            if (statisticsBackup != null) {
                tvLikeCount.setText(statisticsBackup.getPraiseCount()<=0?"0":statisticsBackup.getPraiseCount()+"");
            }
            tvHead.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (creatorBackup != null) {
                        UserPage.start(creatorBackup.getId());
                    }
                }
            });
            tvUserName.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (creatorBackup != null) {
                        UserPage.start(creatorBackup.getId());
                    }

                }
            });
        }
    }






}
